import React, { useState, useEffect, useRef } from 'react';
import {
  Button,
  Checkbox,
  Form,
  Input,
  InputNumber,
  message,
  Select,
  Space,
  Tabs,
  Modal,
  Popconfirm,
} from 'antd';
import { FormattedMessage, useIntl } from 'umi';
import { EditableProTable } from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';
import request from '@/utils/request';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import QuerySelect from '@/components/QuerySelect';

const { TabPane } = Tabs;
const { confirm } = Modal;
const apiURL = '/api/services/app/JobMtl/';

const JobMtlEdit = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [defTab, setDefTab] = useState('MTL1');
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [asmList, setAsmList] = useState([]);
  const [booList, setBooList] = useState([]);
  const [record, setRecord] = useState<any>({});
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [currAsmSeq, setCurrAsmSeq] = useState(null);
  const formRef = useRef<any>();
  const intl = useIntl();

  useEffect(() => {
    initData();
  }, []);

  useEffect(() => {
    const { record, datas } = props;
    setDataSource(datas?.mtls);
    setAsmList(datas?.boms);
    setBooList(datas?.boos);
    setRecord(record);
    formRef.current.setFieldsValue({ JobMtl: record });
  }, [props]);

  const initData = () => {
    const { datas, record } = props;
    setDataSource(datas?.mtls);
    setAsmList(datas?.boms);
    setBooList(datas?.boos);
    setRecord(record);
    formRef.current.setFieldsValue({ JobMtl: record });
  };

  const onChange = (values: any[]) => {
    setDataSource(values);
  };

  const setSelRows = (keys: any, rows: any) => {
    setRecord(rows);
    setSelectedRowKeys(keys);
  };

  const doDel = () => {
    confirm({
      title: intl.formatMessage({id :'pages.warning'}),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({id :'pages.deleteConfirm'}),
      onOk() {
        setLoading(true);
        request(apiURL + 'DelBatch', {
          method: 'POST',
          data: selectedRowKeys,
        }).then((response) => {
          if (response.success) {
            const newDataSource = dataSource.filter((o: any) => selectedRowKeys.indexOf(o.id) < 0);
            setDataSource(newDataSource);
            resetForm();
            if (props.reloadData) {
              props.reloadData('Del', 'JobMtl', newDataSource);
            }
          }
          setLoading(false);
        });
      },
    });
  };

  const setCurrent = (part?: any) => {
    let JobMtl: any = {};
    JobMtl.partNum = part.PartNum;
    JobMtl.partDescription = part.PartDescription;
    JobMtl.ium = part.IUM;
    formRef.current.setFieldsValue({ JobMtl });
  };

  const onFinish = (values: any) => {
    const JobMtl = values.JobMtl;
    saveJobData(JobMtl, apiURL);
  };

  const saveJobData = (data: any, api: string) => {
    let act = 'New';
    let method = 'POST';
    if (data.id) {
      act = 'Update';
      method = 'PUT';
    }
    request(api + act, {
      method: method,
      data: data,
    }).then((response) => {
      if (response && response.success) {
        message.success(intl.formatMessage({id :'pages.save.success'}));
        if (props.reloadData) {
          props.reloadData(act, 'JobMtl', response.result);
        }
      }
      setLoading(false);
    });
  };

  const resetForm = () => {
    const { datas } = props;
    formRef.current.resetFields();
    let JobMtl: any = {};
    JobMtl.jobNum = datas?.jobHead?.jobNum;
    JobMtl.relatedOpRev = datas?.jobHead?.revisionNum;
    formRef.current.setFieldsValue({ JobMtl });
    setRecord(JobMtl);
  };

  const delObj = (id: any) => {
    setSelectedRowKeys([id]);
    doDel();
  };

  const tabSwitch = (key: any) => {
    setDefTab(key);
  };

  const switchEdit = (key: string, record: any) => {
    setDefTab(key);
    setRecord(record);
    formRef.current.setFieldsValue({ JobMtl: record });
  };

  const setDataSourceFun = (params?: any, data?: any) => {
    if (params?.assemblySeq) data = data.filter((o: any) => o.assemblySeq == params.assemblySeq);
    if (params?.mtlSeq) data = data.filter((o: any) => o.mtlSeq == params.mtlSeq);
    if (params?.partNum) data = data.filter((o: any) => o.partNum == params.partNum);
    if (params?.partDescription)
      data = data.filter((o: any) => o.partDescription.indexOf(params.partDescription) >= 0);
    return {
      data,
      total: data.length,
      success: true,
    };
  };

  const onChangeSelect = (e: any) => {
    setCurrAsmSeq(e);
    formRef.current.setFieldsValue({ JobMtl: { relatedOperation: null } });
  };

  const columns: ProColumns[] = [
    {
      title: <FormattedMessage id="pages.jobNum" />,
      dataIndex: 'jobNum',
      width: 100,
      editable: false,
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="pages.assemblySeq" />,
      dataIndex: 'assemblySeq',
      width: 80,
      editable: false,
      valueType: 'digit',
    },
    {
      title: <FormattedMessage id="pages.mtlSeq" />,
      dataIndex: 'mtlSeq',
      width: 65,
      editable: false,
      valueType: 'digit',
    },
    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
      width: 120,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'partDescription',
      ellipsis: true,
      editable: false,
      width: 220,
    },
    {
      title: <FormattedMessage id="pages.requiredQty" />,
      width: 100,
      align: 'center',
      hideInSearch: true,
      dataIndex: 'requiredQty',
    },
    {
      title: <FormattedMessage id="pages.issuedQty" />,
      dataIndex: 'issuedQty',
      editable: false,
      hideInSearch: true,
      width: 80,
    },
    {
      title: <FormattedMessage id="pages.IUM" />,
      width: 80,
      editable: false,
      dataIndex: 'ium',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="pages.operation" />,
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: (text, record, _, action) => [
        <Popconfirm
          key="b1"
          title={<FormattedMessage id="pages.confirmDelete" />}
          onConfirm={() => delObj(record.id)}
        >
          <a>
            <FormattedMessage id="pages.delete" />
          </a>
        </Popconfirm>,
      ],
    },
  ];

  const layout = {
    labelCol: { span: 3 },
    wrapperCol: { span: 15 },
  };

  const currBooList = currAsmSeq ? booList?.filter((o: any) => o.assemblySeq == currAsmSeq) : booList;
  console.log(currBooList);
  

  return (
    <>
      <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={tabSwitch}>
        <TabPane tab={<FormattedMessage id="pages.attribute" />} key="MTL1">
          <Form {...layout} ref={formRef} onFinish={onFinish}>
            <Form.Item name={['JobMtl', 'id']} hidden={true}>
              <Input />
            </Form.Item>
            <Form.Item
              name={['JobMtl', 'jobNum']}
              label={<FormattedMessage id="pages.jobNum" />}
              rules={[{ required: true, message: intl.formatMessage({ id: 'pages.jobNum.required' }) }]}
            >
              <Input disabled style={{ width: 200 }} />
            </Form.Item>
            <Form.Item
              name={['JobMtl', 'assemblySeq']}
              label={<FormattedMessage id="pages.assemblySeq" />}
              rules={[{ required: true, message: intl.formatMessage({ id: 'pages.assemblySeq.required' }) }]}
            >
              <Select style={{ width: 400 }} onChange={onChangeSelect}>
                {asmList?.map((item: any) => {
                  return (
                    <Select.Option value={item.assemblySeq} key={item.id}>
                      {item.assemblySeq} - {item.partNum} - {item.partDescription}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item name={['JobMtl', 'mtlSeq']} label={<FormattedMessage id="pages.mtlSeq" />}>
              <InputNumber min={1} step={1} disabled />
            </Form.Item>
            <Form.Item label={<FormattedMessage id="pages.partNum" />} required={true}>
              <Input.Group compact>
                <Form.Item
                  noStyle
                  name={['JobMtl', 'partNum']}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'pages.partNum.required' }) }]}
                >
                  <Input style={{ width: 200 }} />
                </Form.Item>
                <Form.Item noStyle>
                  <QuerySelect
                    width={680}
                    sysReportName="PartSearch"
                    text={intl.formatMessage({ id: 'pages.query' })}
                    title={intl.formatMessage({ id: 'pages.partNum' })}
                    btntype="primary"
                    setCurrent={setCurrent}
                    scroll={{ x: 'max-content', y: '200px' }}
                    params={{ InActive: 'false' }}
                  />
                </Form.Item>
              </Input.Group>
            </Form.Item>
            <Form.Item
              name={['JobMtl', 'partDescription']}
              label={<FormattedMessage id="pages.partDescription" />}
              rules={[{ required: true, message: intl.formatMessage({ id: 'pages.partDescription.required' }) }]}
            >
              <Input disabled />
            </Form.Item>
            <Form.Item
              style={{ marginBottom: 0 }}
              required={true}
              label={<FormattedMessage id="pages.relatedOperation" />}
            >
              <Input.Group compact>
                <Form.Item
                  name={['JobMtl', 'relatedOperation']}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'pages.relatedOperation.required' }) }]}
                >
                  <Select style={{ width: 200 }}>
                    {currBooList?.map((item: any) => {
                      return (
                        <Select.Option value={item.oprSeq} key={item.id}>
                          {item.assemblySeq} - {item.oprSeq} - {item.opDesc}
                        </Select.Option>
                      );
                    })}
                  </Select>
                </Form.Item>
                <Form.Item
                  name={['JobMtl', 'relatedOpRev']}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'pages.relatedOpRev.required' }) }]}
                >
                  <Input placeholder={intl.formatMessage({ id: 'pages.opRev' })} style={{ width: 80 }} />
                </Form.Item>
              </Input.Group>
            </Form.Item>
            <Form.Item
              label={<FormattedMessage id="pages.qtyPer" />}
              required={true}
              style={{ marginBottom: 0 }}
            >
              <Input.Group compact>
                <Form.Item
                  name={['JobMtl', 'qtyPer']}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'pages.qtyPer.required' }) }]}
                >
                  <InputNumber min={0} style={{ width: 120, marginRight: 10 }} />
                </Form.Item>
                <Form.Item name={['JobMtl', 'fixedQty']} valuePropName="checked">
                  <Checkbox>
                    <FormattedMessage id="pages.fixedQty" />
                  </Checkbox>
                </Form.Item>
              </Input.Group>
            </Form.Item>
            <Form.Item label={<FormattedMessage id="pages.requiredQty" />} required={true}>
              <Input.Group compact>
                <Form.Item
                  noStyle
                  name={['JobMtl', 'requiredQty']}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'pages.requiredQty.required' }) }]}
                >
                  <InputNumber min={0} />
                </Form.Item>
                <Form.Item
                  noStyle
                  name={['JobMtl', 'ium']}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'pages.IUM.required' }) }]}
                >
                  <Input disabled style={{ width: 70 }} placeholder="IUM" />
                </Form.Item>
              </Input.Group>
            </Form.Item>
            <Form.Item style={{ marginBottom: 0 }} wrapperCol={{ offset: 3 }}>
              <Input.Group compact>
                <Form.Item name={['JobMtl', 'issueComplete']} valuePropName="checked">
                  <Checkbox>
                    <FormattedMessage id="pages.issueComplete" />
                  </Checkbox>
                </Form.Item>
                <Form.Item name={['JobMtl', 'direct']} valuePropName="checked">
                  <Checkbox>
                    <FormattedMessage id="pages.directMfg" />
                  </Checkbox>
                </Form.Item>
                <Form.Item name={['JobMtl', 'buyIt']} valuePropName="checked">
                  <Checkbox>
                    <FormattedMessage id="pages.buyIt" />
                  </Checkbox>
                </Form.Item>
                <Form.Item name={['JobMtl', 'rcvInspectionReq']} valuePropName="checked">
                  <Checkbox>
                    <FormattedMessage id="pages.inspectionReq" />
                  </Checkbox>
                </Form.Item>
              </Input.Group>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: layout.labelCol.span }}>
              <Space>
                <Button type="primary" htmlType="submit" loading={loading}>
                  <FormattedMessage id="pages.save" />
                </Button>
                <Button onClick={resetForm}>
                  <FormattedMessage id="pages.new" />
                </Button>
                <Button danger disabled={!record?.id} onClick={() => delObj(record.id)}>
                  <FormattedMessage id="pages.delete" />
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </TabPane>
        <TabPane tab={<FormattedMessage id="pages.list" />} key="MTL2" forceRender>
          <EditableProTable
            rowKey="id"
            scroll={{
              x: 960,
            }}
            loading={loading}
            columns={columns}
            recordCreatorProps={false}
            value={dataSource}
            onChange={onChange}
            request={async (params = {}, sort, filter) => {
              return setDataSourceFun(params, props.datas?.mtls);
            }}
            rowSelection={{
              selectedRowKeys,
              onChange: setSelRows,
            }}
            cardBordered
            search={{
              filterType: 'light',
            }}
            onRow={(record) => {
              return {
                onDoubleClick: (event) => {
                  switchEdit('MTL1', record);
                },
              };
            }}
            tableAlertRender={false}
            tableAlertOptionRender={false}
            editable={{
              type: 'multiple',
              actionRender: (row, config, dom) => [dom.save, dom.cancel],
              onSave: async (rowKey, data, row) => {
                setSelectedRowKeys([]);
              },
              editableKeys: [],
              onChange: (keys: any) => {
                console.log(keys);
              },
            }}
            pagination={{
              pageSize: 10,
            }}
            toolBarRender={() => [
              <Button key="button" type="primary" danger onClick={doDel}>
                <FormattedMessage id="pages.delete.batch" />
              </Button>,
            ]}
          />
        </TabPane>
      </Tabs>
    </>
  );
};

export default JobMtlEdit;
